package com.yc.testupload.controller;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.yc.testupload.util.DatabaseUtil;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 数据库连接测试Servlet
 * 用于测试数据库连接是否正常工作，并查询上传的数据
 */
@WebServlet(name = "databaseTestServlet", value = "/test-db-connection")
public class DatabaseTestServlet extends HttpServlet {

    private static final Logger logger = LogManager.getLogger(DatabaseTestServlet.class);

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();

        out.println("<html><body>");
        out.println("<h1>数据库连接测试</h1>");

        Connection conn = null;
        Statement stmt = null;
        
        try {
            // 调用数据库工具类的测试方法
            boolean isConnected = DatabaseUtil.testConnection();
            
            if (isConnected) {
                out.println("<p style='color:green'>数据库连接成功！</p>");
                
                // 获取连接并查询表信息
                conn = DatabaseUtil.getConnection();
                stmt = conn.createStatement();
                
                // 获取数据库URL和产品信息
                String url = conn.getMetaData().getURL();
                String dbProduct = conn.getMetaData().getDatabaseProductName();
                out.println("<p>当前连接的数据库URL: " + url + "</p>");
                out.println("<p>数据库产品: " + dbProduct + "</p>");
                
                // 查询wk_file表的记录数
                ResultSet rs = stmt.executeQuery("SELECT COUNT(*) AS count FROM wk_file");
                if (rs.next()) {
                    int fileCount = rs.getInt("count");
                    out.println("<p>wk_file表记录总数: " + fileCount + "</p>");
                }
                rs.close();
                
                // 查询wk_wenku表的记录数
                rs = stmt.executeQuery("SELECT COUNT(*) AS count FROM wk_wenku");
                if (rs.next()) {
                    int wenkuCount = rs.getInt("count");
                    out.println("<p>wk_wenku表记录总数: " + wenkuCount + "</p>");
                }
                rs.close();
                
                // 查询wk_wenku表中的最近10条记录
                rs = stmt.executeQuery("SELECT id, title, file_id, wen_type, add_time FROM wk_wenku ORDER BY add_time DESC LIMIT 10");
                
                out.println("<h3>最近上传的10条文档记录:</h3>");
                out.println("<table border='1'><tr>");
                out.println("<th>ID</th><th>标题</th><th>文件ID</th><th>文档类型</th><th>添加时间戳</th></tr>");
                
                boolean hasRecords = false;
                while (rs.next()) {
                    hasRecords = true;
                    out.println("<tr>");
                    out.println("<td>" + rs.getInt("id") + "</td>");
                    out.println("<td>" + rs.getString("title") + "</td>");
                    out.println("<td>" + rs.getInt("file_id") + "</td>");
                    out.println("<td>" + rs.getString("wen_type") + "</td>");
                    out.println("<td>" + rs.getLong("add_time") + "</td>");
                    out.println("</tr>");
                }
                
                if (!hasRecords) {
                    out.println("<tr><td colspan='5'>暂无记录</td></tr>");
                }
                
                out.println("</table>");
                rs.close();
                
            } else {
                out.println("<p style='color:red'>数据库连接失败！</p>");
                out.println("<p>请检查数据库配置是否正确，数据库服务是否正常运行。</p>");
                out.println("<p>配置文件路径: src/main/resources/database.properties</p>");
            }
        } catch (SQLException e) {
            out.println("<p style='color:red'>数据库操作错误: " + e.getMessage() + "</p>");
            logger.error("数据库操作错误", e);
        } catch (Exception e) {
            out.println("<p style='color:red'>测试过程中发生异常: " + e.getMessage() + "</p>");
            logger.error("数据库连接测试异常", e);
        } finally {
            if (stmt != null) {
                try { stmt.close(); } catch (SQLException e) { logger.error("关闭Statement失败", e); }
            }
            if (conn != null) {
                DatabaseUtil.closeConnection(conn);
            }
        }

        out.println("</body></html>");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        doGet(request, response);
    }
}